package com.yanqu.road.server.agent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Descriptors;
import com.yanqu.road.dao.db.*;
import com.yanqu.road.entity.config.beauty.BeautyInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.config.vehicle.VehicleInfo;
import com.yanqu.road.entity.enums.eAgentErrorCode;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.log.LogGreatTradeGoods;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.recharge.RechargeBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.agent.inter.AgentPlayer;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.manger.manor.FishPondMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.activity.*;
import com.yanqu.road.pb.activity.unionwar.UnionWarActivityServerProto;
import com.yanqu.road.pb.beautyescort.BeautyEscortProto;
import com.yanqu.road.pb.common.CommonProto;
import com.yanqu.road.pb.huashigang.HuaShiGangProto;
import com.yanqu.road.pb.zhaoshang.ZhaoShangProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.passRoad.PassRoadModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.recharge.RechargeGainModule;
import com.yanqu.road.server.gameplayer.module.task.TaskModule;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.activity.oldplayerreturn.OldPlayerReturnMgr;
import com.yanqu.road.server.manger.config.BeautyMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.VehicleMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.recharge.RechargeMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class AgentGeneral {

    public static final String IS_INNER_CONFIG_KEY = "isInner";
    public static Logger logger = LogManager.getLogger(AgentGeneral.class.getName());

    /**
     * 玩家每日重置时间减一天
     */
    public static int reducePlayerResetTime(long userId, String param) {
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null != player) {
            player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.ResetAttrTime, System.currentTimeMillis() / 1000 - 24 * 3600);
        }
        return 0;
    }

    public static int setKT(long userId, String param) {
        UserMgr.K = param;
        UserMgr.T = System.currentTimeMillis();
        return 0;
    }

    public static int repair(long userId, String param) {
        if (!param.equals("repairgoods")) {
            return -1;
        }
        logger.error("repairgoods start");
        DBManager db = DatabaseMgr.getDbManager();
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, JSONObject> repairMap = new HashMap<>();
        try {
            db.setConnName(DbNameStrategy.getServerDb());
            String sql = "select * from t_s_repair_actgoods";
            call = db.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                long repairUserId = rs.getLong("userId");
                String repairGoods = rs.getString("goods");
                String serverId = "" + repairUserId;
                serverId = serverId.substring(0, 8);
                if (Objects.equals(serverId, "" + GameServer.getInstance().getServerId())) {
                    JSONObject userObj = new JSONObject();
                    userObj.put("userId", repairUserId);
                    userObj.put("goods", repairGoods);
                    repairMap.put(repairUserId, userObj);
                }
            }
        } catch (Exception e) {
            logger.error("repairgoods error:", e);
        } finally {
            db.closeConnection(call, rs);
        }

        for (JSONObject userObj : repairMap.values()) {
            long repairUserId = userObj.getLongValue("userId");
            String repairGoods = userObj.getString("goods");
            GamePlayer player = GamePlayerMgr.getPlayer(repairUserId);
            if (null == player) {
                continue;
            }

            Property oriReward = PropertyHelper.parseStringToProperty(repairGoods);  //原始奖励
            Property subReward = new Property();
            Property noSubReward = new Property();
            //把珍兽和财神,头像框过滤出来
            for (Map.Entry<Integer, BigInteger> goodsEntry : oriReward.getGoods().entrySet()) {
                Integer goodsId = goodsEntry.getKey();
                BigInteger goodsNum = goodsEntry.getValue();
                if (GoodsMgr.isVehicleGoods(goodsId)) {//珍兽
                    noSubReward.addProperty(goodsId, goodsEntry.getValue());
                } else if (GoodsMgr.isDecorationGoods(goodsId)) {//饰品 称号
                    noSubReward.addProperty(goodsId, goodsEntry.getValue());
                }else if (FishPondMgr.isFishItem(goodsId)){//鱼类
                    noSubReward.addProperty(goodsId, goodsEntry.getValue());
                }else if (GameConfig.FISHPOND_FISH_EXP_ITEM_ID == goodsId){//鱼食
                    noSubReward.addProperty(goodsId, goodsEntry.getValue());
                }else if (GoodsMgr.isCricketGoods(goodsId)){//蛐蛐
                    noSubReward.addProperty(goodsId, goodsEntry.getValue());
                }else {//背包道具
                    subReward.addProperty(goodsId, goodsNum);
                }
            }

            //道具扣到负数
            player.getModule(CurrencyModule.class).forceRemoveCurrencyCanNegative(subReward);

            player.saveData();

            db = DatabaseMgr.getDbManager();
            call = null;
            try {
                db.setConnName(DbNameStrategy.getServerDb());
                String updateSql = "update t_s_repair_actgoods set subGoods=?,noSubGoods=? where userId=?";
                call = db.getConnection().prepareCall(updateSql);
                call.setString(1, PropertyHelper.parsePropertyToString(subReward));
                call.setString(2, PropertyHelper.parsePropertyToString(noSubReward));
                call.setLong(3, repairUserId);

                if (call.executeUpdate() <= 0) {
                    logger.error("repairgoods update err userId:{}", repairUserId);
                }
            } catch (Exception e) {
                logger.error("repairgoods error:", e);
            } finally {
                db.closeConnection(call, null);
            }

        }
        logger.error("repairgoods end");
        return 0;
    }

    /**
     * 需要用到clickhouse查询参考这个方法
     */
    public static void repairClickHouse() {
        String url = "jdbc:clickhouse://10.1.102.211:8123/dzg_game_log?user=root&password=yanqu@123";
        try {
            //    Class.forName("com.clickhouse.jdbc.ClickHouseDriver");
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            Connection conn = DriverManager.getConnection(url, "root", "yanqu@123");
            ResultSet rs = conn.createStatement().executeQuery("SELECT * from t_l_cricket_get_dst");
            while (rs.next()) {
                int cricketId = rs.getInt("cricketId");
                System.out.println(cricketId);
            }
        } catch (SQLException e) {
            logger.error("clickhouse jdbc error:", e);
        }
    }


    public static int repairRemoveGood(long userId, String param) {
        if (!param.equals("repairRemoveGood")) {
            return -1;
        }
        logger.warn("repair start");
        DBManager db = DatabaseMgr.getDbManager();
        ResultSet rs = null;
        CallableStatement call = null;



        Map<Long, String> userRepairMap = new HashMap<>();
        try {
            db.setConnName(DbNameStrategy.getServerDb());
            String sql = "select * from t_s_remove_good " +
                    "LEFT JOIN t_s_remove_result on t_s_remove_result.userId = t_s_remove_good.userId " +
                    "WHERE removeResult is null";
            call = db.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                long removeUserId = rs.getLong("userId");
                String removeReward = rs.getString("reward");
                userRepairMap.put(removeUserId,removeReward);
            }
        } catch (Exception e) {
            logger.error("repair error:", e);
        } finally {
            db.closeConnection(call, rs);
        }



        //玩家入库数据,记录玩家未扣除的奖励和需不要补发的奖励
        Map<Long, List<String>> userInsertDataMap = new HashMap<>();
        for (long repairUserId : userRepairMap.keySet()) {
            String reward = userRepairMap.get(repairUserId);
            Property rewardPro = PropertyHelper.parseStringToProperty(reward);

            //封号踢下线
            UserMgr.setBlackListEndTime(repairUserId, System.currentTimeMillis() + DateHelper.DAY_MILLIONS);
            //踢下线
            AgentPlayer.executeKillPlayer(repairUserId);

            UserInfo userInfo = UserMgr.getUserInfo(repairUserId);
            if (null == userInfo) {
                continue;
            }
            GamePlayer player = GamePlayerMgr.getPlayer(repairUserId);
            if (null == player) {
                continue;
            }
            BagModule bagModule = player.getModule(BagModule.class);
            CurrencyModule currencyModule = player.getModule(CurrencyModule.class);//已领取的要扣奖励
            //剩余未扣的奖励
            Property remainRemove = new Property();
            for (Map.Entry<Integer, BigInteger> goodsEntry : rewardPro.getGoods().entrySet()) {
                int goodsId = goodsEntry.getKey();
                BigInteger goodsNum = goodsEntry.getValue();
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                if (null != goodsInfo) {
                    if (GoodsMgr.isVehicleGoods(goodsId)) {//珍兽
                        remainRemove.addProperty(goodsId, BigInteger.valueOf(1));
                    } else if (GoodsMgr.isDecorationGoods(goodsId)) {//饰品 称号
                        remainRemove.addProperty(goodsId, BigInteger.valueOf(1));
                    } else {//背包道具
                        long removeNum = goodsNum.longValue();
                        long remainRemoveNum = removeNum;
                        UserBagItem userBagItem = bagModule.getUserBagItem(goodsId);
                        if (null != userBagItem) {
                            if (userBagItem.getNum() < removeNum) {//背包道具不够扣
                                remainRemoveNum = removeNum - userBagItem.getNum();
                                removeNum = userBagItem.getNum();
                                remainRemove.addProperty(goodsId, BigInteger.valueOf(remainRemoveNum));
                            }

                            do {
                                if (removeNum > 0) {
                                    Property removeProp = new Property(goodsId, BigInteger.valueOf(removeNum));
                                    if (currencyModule.removeCurrency(removeProp, eLogMoneyType.Bag, eLogMoneyType.BagBackendChange)) {
                                        //扣除成功
                                        logger.info("repair delete bagItem, userId:{},goodsId{},num:{}", repairUserId, goodsId, removeNum);
                                        break;
                                    } else {
                                        removeNum--;
                                        if (removeNum <= 0) {
                                            break;
                                        }
                                    }
                                } else {
                                    break;
                                }
                            } while (true);
                        } else {
                            remainRemove.addProperty(goodsId, BigInteger.valueOf(remainRemoveNum));
                        }
                        List<String> resultList = new ArrayList<>();
                        resultList.add(reward);
                        resultList.add(PropertyHelper.parsePropertyToString(remainRemove));
                        userInsertDataMap.put(repairUserId,resultList);
                    }
                }
            }


            //解封
            UserMgr.setBlackListEndTime(repairUserId, 0);
            player.saveData();
        }


        db.setConnName(DbNameStrategy.getServerDb());
        String insertSql = "insert into t_s_remove_result(userId,removeResult,remainRemove)values(?,?,?)";

        try {
            for (long repairUserId : userInsertDataMap.keySet()) {
                int i = 1;
                Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
                para.put(i++, new DbParameter(Types.BIGINT, repairUserId));
                para.put(i++, new DbParameter(Types.VARCHAR, userInsertDataMap.get(repairUserId).get(0)));
                para.put(i++, new DbParameter(Types.VARCHAR, userInsertDataMap.get(repairUserId).get(1)));
                if (db.executeNoneQuery(insertSql, para) > 0) {
                    continue;
                }
            }
        } catch (Exception e) {
            logger.error("repair mail error:", e);
        }

        logger.warn("repair mail end");
        return 0;
    }

    public static int repairHuaShiGangActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        HuaShiGangProto.HuaShiGangHelpCode.Builder builder = HuaShiGangProto.HuaShiGangHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C2_HUA_SHI_GANG_HELPER_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairGhostActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        GhostActivityProto.GhostHelpCode.Builder builder = GhostActivityProto.GhostHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_GHOST_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairSuoYaoActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        SuoYaoActivityProto.CrossSuoYaoHelpCode.Builder builder = SuoYaoActivityProto.CrossSuoYaoHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_SUOYAO_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }


    public static int repairSpringDinnerActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        SpringDinnerProto.CrossSpringDinnerHelpCode.Builder builder = SpringDinnerProto.CrossSpringDinnerHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_SPRINGDINNER_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairFireWorkActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        FireWorkProto.CrossFireWorkFireWorkHelpCode.Builder builder = FireWorkProto.CrossFireWorkFireWorkHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairConditionActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        FireWorkProto.CrossFireWorkFireWorkHelpCode.Builder builder = FireWorkProto.CrossFireWorkFireWorkHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CONDITION_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairShuihuActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        ShuiHuActivityProto.ShuiHuHelpCode.Builder builder = ShuiHuActivityProto.ShuiHuHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_SHUIHU_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairBusyFarmingActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        BusyFarmingProto.BusyFarmingActivityHelpCode.Builder builder = BusyFarmingProto.BusyFarmingActivityHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_BUSY_FARMING_ACTIVITY_HELP_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairDouLuoDaLuActivity(long userId, String param) {
        TableInfo tableInfo = GameServer.getInstance().getDbTableInfoMgr().getTableInfoByClass(LogGreatTradeGoods.class);
        if(tableInfo != null){
            tableInfo.setSaveSql("INSERT INTO `t_l_great_trade_goods` (`userId`, `activityId`, `goodsId`, `get`, `num`, `yingli`, `sliver`, `bagNum`, `health`, `prestige`, `title`, `age`, `assets`, `times`, `time`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
        }
        return 0;
    }

    public static int repairUnionWarActivity(long userId, String param) {
        List<Integer> list = StringUtils.stringToIntegerList(param, "\\|");
        UnionWarActivityServerProto.UnionWarActivityHelpCode.Builder builder = UnionWarActivityServerProto.UnionWarActivityHelpCode.newBuilder();
        builder.setType(list.get(0));
        builder.setActivityId(list.get(1));

        //YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_WAR_HELPER_CODE, builder);
        //GamePlayerMgr.sendChannelPacket(0, pbMsg);
        GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_UNION_WAR_HELPER_CODE, builder, 0, builder.getActivityId(), 0);
        return 0;
    }

    public static int repairZhaoShangSystem(long userId, String param){
        ZhaoShangProto.ZhaoShangHelpCode.Builder builder = ZhaoShangProto.ZhaoShangHelpCode.newBuilder();
        builder.setUserId(userId);
        builder.setParam(param);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C2_ZHAO_SHANG_HELPER_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    public static int repairBeautyEscortSystem(long userId, String param){
        BeautyEscortProto.BeautyEscortHelpCode.Builder builder = BeautyEscortProto.BeautyEscortHelpCode.newBuilder();
        builder.setUserId(userId);
        builder.setParam(param);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C_BEAUTY_ESCORT_HELPER_CODE, builder);
        GamePlayerMgr.sendPacket(0, pbMsg);
        return 0;
    }

    /**
     * 重传分组榜单-埋点
     */
    public static int reUploadDataAnalyticsRandData(long userId, String param){
        //区服
        if("1".equals(param)){
            DataAnalyticsMgr.trackUserRankEvent();
        }else if("2".equals(param)){
            //分组
            CommonProto.NullValueMsg.Builder builder = CommonProto.NullValueMsg.newBuilder();
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C_DATA_ANALYTICS_RE_UPLOAD_RANK, builder);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
        return 0;
    }

    /**
     * 清除埋点缓存队列
     */
    public static int removeDataAnalyticsQueueData(long userId, String param){
        DataAnalyticsMgr.repair(param);
        return 0;
    }

    /**
     * 首充重置（全部，分游戏内首充、第三方首充）
     * @param userId
     * @param param
     * @return
     */
    public static int resetFirstRecharge(long userId, String param) {
        int resetAll = 0;
        int markIndex = 0;
        String[] paramArr = param.split("\\|");
        if(paramArr.length > 1) {
            resetAll = Integer.parseInt(paramArr[0]);
            if(0 == resetAll) {
                markIndex = Integer.parseInt(paramArr[1]);
            }
        }
        if(resetAll > 0) {//全部重置
            RechargeBussiness.resetFirstRecharge();
            if(RechargeMgr.isUseNewMultiple()) {
                RechargeBussiness.resetAllFirstRecharge();
            }
            synchronized (GamePlayerMgr.getPlayerMap()) {
                for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                    player.getModule(RechargeGainModule.class).resetAll();
                }
            }
        }else {//重置部分
            int value = (int) Math.pow(2, markIndex);
            RechargeBussiness.resetRechargeGain(value);
            if(RechargeMgr.isUseNewMultiple()) {
                RechargeBussiness.resetRechargeTimes(markIndex);
            }
            synchronized (GamePlayerMgr.getPlayerMap()) {
                for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                    player.getModule(RechargeGainModule.class).reset(markIndex);
                }
            }
        }
        return 1;
    }

    /**
     * 重置操作系统日期、时间
     * @param userId
     * @param param  2024/12/11 8:23:33
     * @return
     */
    public static int modifyServerDate(long userId, String param){
        String osName = System.getProperty("os.name");
        try {
            param = param.replaceAll("/","-");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            format.parse(param);
        } catch (ParseException e) {
            e.printStackTrace();
            return -1;
        }
        try {
            String[] dt = param.split(" ");
            String cmdDate = "";
            String cmdTime = "";
            if(osName.matches("^(?i)Windows.*$")){
                cmdDate = "cmd /c date " + dt[0];
                cmdTime = "cmd /c time " + dt[1];
            }else{
                cmdDate = "date -s " + dt[0].replaceAll("-", "");
                cmdTime = "date -s " + dt[1];
            }
            Runtime.getRuntime().exec(cmdDate);
            Runtime.getRuntime().exec(cmdTime);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    /**
     * 重新加载数据配置
     * @param userId
     * @param param  excelDir文件路径（服务器）
     * @return
     */
    public static int reloadGameConfigTable(long userId, String param){

        return 0;
    }


    /**
     * 是否开启内网测试
     * @return
     */
    private static boolean isInnerTest(){
        String isInner = ConfigHelper.getValue(IS_INNER_CONFIG_KEY);
        if (StringUtils.isNullOrEmpty(isInner)) {
            return false;
        }
        if (!isInner.equals("1")) {
            return false;
        }
        return true;
    }

    /**
     * 个人日重置
     * @param userId
     * @return
     */
    public static int resetOneDay(long userId){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        player.getModule(TaskModule.class).resetOneDay();
        return 0;
    }

    /**
     * 关卡进度指定挑战
     * @param param  100:1
     * @return
     */
    public static int jumpToPassRoad(long userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        String[] params = param.split(":");
        if(params.length < 2){
            return -1;
        }
        player.getModule(PassRoadModule.class).jumpToPassRoad(Integer.valueOf(params[0]),Integer.valueOf(params[1]));
        return 0;
    }

    public static int unionWarActivityAutoDispatch(long userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(player.getUserInfo().getUnionUid());
        for(Map.Entry<Long, CrossUnionMember> memberEntry : unionMemberMap.entrySet()){
            UnionMember member = memberEntry.getValue();
            player = GamePlayerMgr.getPlayer(member.getUserId());
            if(player != null){
                //player.getModule(UnionWarActivityModule.class).autoDispatchPatrons(player);
            }
        }
        return 0;
    }

    /**
     * 增加或者较少资源（如元宝、银两等)
     * @param userId
     * @param param  resourcesId:num;resourcesId2:num2    如 101000:100000 或者  101000:-1000000
     * @return
     */
    public static int addOrRemoveResources(long userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        if(StringUtils.isNullOrEmpty(param)){
            return -1;
        }
        Property addProperty = new Property();
        Property removeProperty = new Property();
        String[] groupArr = param.split(";");
        for(String group : groupArr) {
            if (StringUtils.isNullOrEmpty(group) || !group.contains(":")) {
                return -1;
            }
            String[] goodsArr = group.split(":");
            if (goodsArr.length < 2) {
                return -1;
            }
            int id = Integer.valueOf(goodsArr[0]);
            long num = Long.valueOf(goodsArr[1]);
            if(num > 0){
                addProperty.addProperty(id, BigInteger.valueOf(num));
            }else{
                removeProperty.addProperty(id, BigInteger.valueOf(Math.abs(num)));
            }
        }
        player.getModule(CurrencyModule.class).addCurrency(addProperty, eLogMoneyType.GM, eLogMoneyType.GmSend);
        player.getModule(CurrencyModule.class).removeCurrency(removeProperty, eLogMoneyType.GM, eLogMoneyType.GmSend);
        return 0;
    }

    /**
     * 增加指定门客、美人、珍兽
     * @param userId
     * @param param（goodsId:num;goodsId2:num2 or 0:num）
     * @return
     */
    public static int addPBV(long userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        Property property = new Property();
        if(StringUtils.isNullOrEmpty(param)){
            return -1;
        }
        String[] groupArr = param.split(";");
        for(String group : groupArr){
            if(StringUtils.isNullOrEmpty(group) || !group.contains(":")){
                return -1;
            }
            String[] goodsArr = group.split(":");
            if(goodsArr.length < 2){
                return -1;
            }
            int id = Integer.valueOf(goodsArr[0]);
            long num = Long.valueOf(goodsArr[1]);
            if(id == 0){
                for(PatronsInfo patrons : PatronsMgr.getPatronsInfoMap().values()){
                    property.addProperty(patrons.getId(), BigInteger.ONE);
                }
                for(BeautyInfo beauty : BeautyMgr.getBeautyInfoMap().values()){
                    property.addProperty(beauty.getBeautyId(), BigInteger.ONE);
                }
                for(VehicleInfo vehicle : VehicleMgr.getVehicleInfoMap().values()){
                    property.addProperty(vehicle.getId(), BigInteger.valueOf(num));
                }
            }else {
                property.addProperty(id, BigInteger.valueOf(num));
            }
        }
        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.GM, eLogMoneyType.GmSend);
        return 0;
    }


    public static int sendProto(long userId, String param) {
        try {
            if(!isInnerTest()){
                return -1;
            }
            String path = "C:\\dzg_backend_2\\config\\sendProto.properties";
            InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
            Properties properties = new Properties();
            properties.load(inputStream);
            String param2 = JSON.toJSONString(properties);
            JSONObject jsonObject = JSON.parseObject(param2);
            int code = jsonObject.getInteger("code");
            String packageName = jsonObject.getString("packageName");
            String pbClassName = jsonObject.getString("pbClassName");
            String messageName = jsonObject.getString("messageName");
            String className = "com.yanqu.road.pb." + packageName + (packageName.isEmpty() ? "" : ".") + pbClassName + "$" + messageName;
            Class<?> cl = Class.forName(className);
            Method method = cl.getMethod("newBuilder");
            Object invoke = method.invoke(null, null);
            AbstractMessage.Builder builder = (AbstractMessage.Builder) invoke;
            Descriptors.Descriptor descriptor = builder.getDescriptorForType();
            JSONObject msgParam = jsonObject.getJSONObject("msgParam");
            for (Map.Entry<String, Object> entry : msgParam.entrySet()) {
                Descriptors.FieldDescriptor fieldDescriptor = descriptor.findFieldByName(entry.getKey());
                if (fieldDescriptor == null) {
                    logger.error("msg param key no found, key:{}", entry.getKey());
                    continue;
                }
                Descriptors.FieldDescriptor.JavaType type = fieldDescriptor.getJavaType();

                boolean isRepeated = fieldDescriptor.isRepeated();
                if (isRepeated) {
                    String value = String.valueOf(entry.getValue());
                    String[] split = value.split(",");
                    for (String str : split) {
                        Object strValue = getValue(String.valueOf(str), type);
                        if (strValue == null) {
                            continue;
                        }
                        builder.addRepeatedField(fieldDescriptor, strValue);
                    }
                } else {
                    Object value = getValue(String.valueOf(entry.getValue()), type);
                    builder.setField(fieldDescriptor, value);
                }
            }
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            player.sendPacket(code, builder);
        } catch (Exception ex) {
            logger.error(ex);
        }
        return 0;
    }

    private static Object getValue(String value, Descriptors.FieldDescriptor.JavaType type) {
        switch (type) {
            case INT:
                return Integer.parseInt(value);
            case LONG:
                return Long.valueOf(value);
            case STRING:
                return value;
            case BOOLEAN:
                return Boolean.valueOf(value);
            default:
                return null;
        }
    }

    /**
     * 增加道具（非门客、美人、珍兽、元宝 银两、饰品）
     * @param userId
     * @param param（goodsId:num;goodsId2:num2  or 0:num）
     * @return
     */
    public static int addGoods(long userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        if(StringUtils.isNullOrEmpty(param)){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(null == player) {
            return -1;
        }
        String[] groupArr = param.split(";");
        Property property = new Property();
        for(String group : groupArr){
            if(StringUtils.isNullOrEmpty(group) || !group.contains(":")){
                return -1;
            }
            String[] goodsArr = group.split(":");
            if(goodsArr.length < 2){
                return -1;
            }
            int id = Integer.valueOf(goodsArr[0]);
            long num = Long.valueOf(goodsArr[1]);
            if(id == 0){
                for(GoodsInfo goods : GoodsMgr.getGoodsInfoMap().values()){
                    //过滤  称号   头像框
                    if(GoodsMgr.isDecorationGoods(goods.getGoodsId())){
                        continue;
                    }
                    if(GoodsMgr.isVehicleGoods(goods.getGoodsId())){  //过滤珍兽
                        continue;
                    }
                    if(GoodsMgr.isPatronsGoods(goods.getGoodsId())){  //过滤门客
                        continue;
                    }
                    if(GoodsMgr.isBeautyGoods(goods.getGoodsId())){   //过滤美女
                        continue;
                    }
                    property.addProperty(goods.getGoodsId(), BigInteger.valueOf(num));
                }
            }else{
                property.addProperty(id, BigInteger.valueOf(num));
            }
        }
        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.GM, eLogMoneyType.GmSend);
        return 0;
    }

    /**
     * 跳转至主线任务
     * @param userId
     * @param param  主线任务ID
     * @return
     */
    public static int jumpToMainTask(long  userId, String param){
        if(!isInnerTest()){
            return -1;
        }
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        int ret = player.getModule(TaskModule.class).jumpToMainTask(Integer.valueOf(param));
        return ret;
    }

    public String refreshOldReturnWhite(long userId, String param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        OldPlayerReturnMgr.refreshWhiteMap();
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public static int repairOpenId(long userId, String param) {
        String[] paramArr = param.split(";");
        if (!paramArr[0].equals("repairOpenId")) {
            return -1;
        }
        UserInfo userInfo  = UserMgr.getUserInfo(userId);
        if(null != userInfo && !StringUtils.isNullOrEmpty(paramArr[1])){
            userInfo.setOpenId(paramArr[1]);
        }
        UserBussiness.updateUserInfo(userInfo);
        return 0;
    }
}
